package com.zrrd.straw1.controller;


import com.zrrd.straw1.entity.Comment;
import com.zrrd.straw1.service.ICommentService;
import com.zrrd.straw1.vo.CommentVo;
import com.zrrd.straw1.vo.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;


@RestController
@RequestMapping("/comments")
public class CommentController {
    @Autowired
    ICommentService commentService;

    @PostMapping("/{id}/update")
    public Result<Comment> udpateComment(@PathVariable Integer id ,
                                         @AuthenticationPrincipal UserDetails userDetails,
                                         @Validated CommentVo commentVo,
                                         BindingResult result){
        //如果前端发送过来的数据，验证有问题
        if(result.hasErrors()){
            String message = result.getFieldError().getDefaultMessage();
            return Result.unprocesableEntity(message);
        }
        Comment comment = commentService.updateComment(id,commentVo,userDetails.getUsername());
        return Result.ok(comment);


    }

    @GetMapping("/{commentId}/delete")
    public Result removeComment( @PathVariable Integer commentId,
                                 @AuthenticationPrincipal UserDetails userDetails){
        boolean isDelete = commentService.removeComment(commentId , userDetails.getUsername());
        if( isDelete ){
            return Result.gone("删除成功");
        }else{
            return Result.notFound("没有删除指定的评论");
        }
    }



    /**
     * 添加评论方法
     * @param commentVo
     * @param bindingResult
     * @param userDetails
     * @return
     */
    @PostMapping
    public Result<Comment> postComment(@Validated CommentVo commentVo,
                                       BindingResult bindingResult,
                                       @AuthenticationPrincipal UserDetails userDetails){
        //后端数据验证，这个动作写了很多遍，基本没什么变化
        if( bindingResult.hasErrors()){
            String msg = bindingResult.getFieldError().getDefaultMessage();
            return Result.unprocesableEntity(msg);
        }
        Comment comment = commentService.saveComment( commentVo, userDetails.getUsername());
        //后续还需要交给业务层保存到数据库
        return Result.created(comment);
    }
}
